package main

import (
	"flag"
	"fmt"
	"html/template"
	"os"
	"text/tabwriter"
)

func recordList() {
	fs := flag.NewFlagSet("record-list", flag.ExitOnError)
	fs.Usage = func() {
		fmt.Fprintln(os.Stderr, `Usage: dnspod.cmd record-list OPTIONS

OPTIONS:`)
		fs.PrintDefaults()
	}
	parseCommonArgs(fs)
	domain := fs.String("domain", "", "records from domain")
	keyword := fs.String("keyword", "", "query keyword")
	parseArgs(fs)

	defaultFormats := "{{.Name}}\t{{.Type}}\t{{.Value}}"
	if allowFormats {
		w := tabwriter.NewWriter(os.Stdout, 0, 0, 8, ' ', 0)
		fmt.Fprintln(w, "Allow:\t"+defaultFormats+"\t{{.ID}}\t")
		fmt.Fprintln(w, "Default:\t"+defaultFormats+"\t")
		w.Flush()
		os.Exit(0)
	}

	if len(confDir) == 0 {
		fmt.Println("Missing conf param")
		os.Exit(1)
	}
	if len(*domain) == 0 {
		fmt.Println("Missing domain param")
		os.Exit(1)
	}

	LoadConf(confDir)

	if len(format) > 0 {
		defaultFormats = format
	}
	tpl, err := template.New("row").Parse(defaultFormats)
	assert(err)

	_, records, err := cli.RecordList(*domain, *keyword)
	assert(err)

	w := tabwriter.NewWriter(os.Stdout, 0, 0, 8, ' ', 0)
	defer w.Flush()
	if !noHeader {
		assert(tpl.Execute(w, map[string]string{
			"ID":    "id",
			"Name":  "name",
			"Type":  "type",
			"Value": "value",
		}))
		fmt.Fprintln(w)
	}
	for _, record := range records {
		assert(tpl.Execute(w, record))
		fmt.Fprintln(w)
	}
}
